package com.litchishell.easy;

import java.util.Arrays;

/**
 * @author LitchiShell
 * @description: 题目28：实现strStr()
 * @create 2022-08-23
 */
public class Solution009 {

    // 常规题解
    public static int strStr(String haystack, String needle) {
        if (needle == null || needle.length() == 0) {
            return 0;
        }
        if (haystack == null || haystack.length() == 0 || needle.length() > haystack.length()) {
            return -1;
        }
        char[] haystackChars = haystack.toCharArray();
        char[] needleChars = needle.toCharArray();
        for (int i = 0; i < haystackChars.length; i++) {
            if (haystackChars[i] == needleChars[0] && (haystackChars.length - i >= needleChars.length)) {
                char[] chars = Arrays.copyOfRange(haystackChars, i, i + needleChars.length);
                if (isSame(chars, needleChars)) {
                    return i;
                }
            }
        }
        return -1;
    }

    public static boolean isSame(char[] haystackChars, char[] needleChars) {
        for (int i = 0; i < needleChars.length; i++) {
            if (haystackChars[i] != needleChars[i]) {
               return false;
            }
        }
        return true;
    }

    // 官方题解，还有一种Knuth-Morris-Pratt 算法
    public int strStrCopy(String haystack, String needle) {
        int n = haystack.length(), m = needle.length();
        for (int i = 0; i + m <= n; i++) {
            boolean flag = true;
            for (int j = 0; j < m; j++) {
                if (haystack.charAt(i + j) != needle.charAt(j)) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                return i;
            }
        }
        return -1;
    }
}
